package ahot;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestDistinct {
    public static void main(String[] args) {
        int[] arr1 = {2, 3, 4, 4, 5, 9, 10};
        int[] arr2 = {0, 1,1, 2, 2, 3, 4, 5, 6, 7, 7, 22};
        int[] result = mergeAndSort(arr1, arr2);
        System.out.println("hadSorted = " + Arrays.toString(result));
    }

    private static int[] mergeAndSort(int[] arr1, int[] arr2) {
        //创建辅助集合，其实数组创建新的数组也行，new int[A.length+arr2.length]
        List<Integer> list = new ArrayList<>();
        int index = 0, p1 = 0, p2 = 0;
        //先将arr1或者arr2中的首个元素中的最小值添加到list
        int min = arr1[p1] < arr2[p2] ? arr1[p1] : arr2[p2];
        list.add(min);
        //当没有遍历完arr1或者arr2中任意一个数组时执行
        while (p1 < arr1.length && p2 < arr2.length) {
            //拿到当前指针的最小值
            int tmp = arr1[p1] < arr2[p2] ? arr1[p1++] : arr2[p2++];
            //判断list中是否已经添加了此元素
            if (tmp > list.get(index)) {
                list.add(tmp);
                //每次添加元素后指针后移
                index++;
            }
        }
        //当arr2中元素添加完，只剩arr1中元素时
        while (p1 < arr1.length) {
            int tmp = arr1[p1++];
            if (tmp > list.get(index)) {
                list.add(tmp);
                index++;
            }
        }
        //当arr1中元素添加完，只剩arr2中元素时
        while (p2 < arr2.length) {
            int tmp = arr2[p2++];
            if (tmp > list.get(index)) {
                list.add(tmp);
                index++;
            }
        }
        //将list中元素重新移回到数组，如果刚开始创建的是数组，那么就不用这一步了
            /*int[] result = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                result[i] = list.get(i);
            }*/
        //Integer[] integers = list.toArray(new Integer[0]);

        int[] result = list.stream().mapToInt(Integer::intValue).toArray();
        return result;

    }
}